package com.ruoyi.task.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.task.domain.EquipmentConfig;
import com.ruoyi.task.domain.SubBankServerConfig;
import com.ruoyi.task.domain.TaskConfig;
import com.ruoyi.task.domain.TaskDetail;
import com.ruoyi.task.service.IEquipmentConfigService;
import com.ruoyi.task.service.ISubBankServerConfigService;
import com.ruoyi.task.service.ITaskDetailService;
import com.ruoyi.task.service.ITaskTypeService;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("01")
@Slf4j
public class TaskTypeEveryDayServiceImpl implements ITaskTypeService {

    @Autowired
    ITaskDetailService taskDetailService;

    @Autowired
    IEquipmentConfigService equipmentConfigService;

    @Autowired
    ISubBankServerConfigService subBankServerConfigService;

    public void deal (TaskConfig taskConfig) {
        try {
            log.info("taskConfig===" + taskConfig);
            long equipmentId = taskConfig.getEquipmentId();
            EquipmentConfig equipmentConfig = equipmentConfigService.selectEquipmentConfigByEquipmentId(
                    equipmentId);
            log.info("equipmentConfig===" + equipmentConfig);
            //通过配置信息插入任务明细表
            TaskDetail taskDetail = new TaskDetail();
            taskDetail.setSubBankCode(equipmentConfig.getSubBankCode());
            taskDetail.setSubBankName(equipmentConfig.getSubBankName());
            taskDetail.setBankCode(equipmentConfig.getBankCode());
            taskDetail.setBankName(equipmentConfig.getBankName());
            taskDetail.setEquipmentIp(equipmentConfig.getEquipmentIp());
            taskDetail.setEquipmentType(equipmentConfig.getEquipmentType());
            taskDetail.setEquipmentChannel(taskConfig.getChannelId());

            String currentDay = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            taskDetail.setStartTime(currentDay + " " + taskConfig.getStartTime());
            taskDetail.setStartEnd(currentDay + " " + taskConfig.getStartEnd());
            taskDetail.setFrequencyType(taskConfig.getFrequencyType());
            taskDetail.setScenariosType(taskConfig.getScenariosType());
            taskDetail.setFps(taskConfig.getFps());
            taskDetail.setSecondMerge(taskConfig.getSecondMerge());
            taskDetail.setChannelRemark(taskConfig.getChannelRemark());
            //任务状态（00-初始化 01-视频采集中 02-视频采集完成 03-视频采集失败 04-视频分析中 05-视频分析完成 06-视频分析失败）
            taskDetail.setTaskStatus("00");
            taskDetail.setTaskType(taskConfig.getTaskType());
            taskDetailService.insertTaskDetail(taskDetail);
            long taskDetailId = taskDetail.getTaskDetailId();

            SubBankServerConfig subBankServerConfig = new SubBankServerConfig();
            subBankServerConfig.setSubBankCode(taskDetail.getSubBankCode());
            List<SubBankServerConfig> subBankServerConfigList = subBankServerConfigService.selectServerConfigList(
                    subBankServerConfig);
            String subServerIp = "";
            if (!CollectionUtils.isEmpty(subBankServerConfigList)) {
                SubBankServerConfig serverConfig = subBankServerConfigList.get(0);
                subServerIp = serverConfig.getServerIp();
            }

            SubBankServerConfig bankServerConfig = new SubBankServerConfig();
            bankServerConfig.setSubBankCode(taskConfig.getBankCode());

            List<SubBankServerConfig> bankServerConfigList = subBankServerConfigService.selectServerConfigList(
                    bankServerConfig);
            String bankServerIp = "";
            if (!CollectionUtils.isEmpty(bankServerConfigList)) {
                SubBankServerConfig serverConfig = bankServerConfigList.get(0);
                bankServerIp = serverConfig.getServerIp();
            }
            //发送任务接口
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 3. 构建表单数据（文件 + 其他字段）
            Map<String, Object> body = new HashMap<>();
            body.put("serviceIpAddress", bankServerIp);
            body.put("sceneIds", taskConfig.getScenariosType());
            body.put("subBankCode", taskDetail.getBankCode());
            body.put("fps", taskDetail.getFps());
            body.put("videoFps", taskDetail.getFps());
            body.put("channelId", taskDetail.getEquipmentChannel());
            body.put("startTime", taskDetail.getStartTime());
            body.put("endTime", taskDetail.getStartEnd());
            body.put("secondMerge", taskDetail.getSecondMerge());
            body.put("videoEquipmentIp", taskDetail.getEquipmentIp());
            body.put("taskType", taskDetail.getTaskType());

            log.info("pushNvrVideoTask params = {}", JSON.toJSONString(body));

            // 4. 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity =
                    new HttpEntity<>(body, headers);
            String uploadUrl = "http://" + subServerIp + ":8081" + "/video/pushNvrVideoTask";
            log.info("uploadUrl==" + uploadUrl);
            ResponseEntity<ServiceResponse> response = restTemplate.exchange(
                    uploadUrl,
                    HttpMethod.POST,
                    requestEntity,
                    ServiceResponse.class
            );
            String code = Objects.requireNonNull(response.getBody()).getCode();
            log.info("code:" + code);
            if ("0".equals(code)) {
                String taskId = Objects.requireNonNull(response.getBody()).getData();
                TaskDetail taskDetailUpdate = new TaskDetail();
                taskDetailUpdate.setTaskDetailId(taskDetailId);
                taskDetailUpdate.setTaskId(taskId);
                taskDetailUpdate.setTaskStatus("01");
                taskDetailService.updateTaskDetail(taskDetailUpdate);
            } else {
                TaskDetail taskDetailUpdate = new TaskDetail();
                taskDetailUpdate.setTaskDetailId(taskDetailId);
                taskDetailUpdate.setTaskStatus("03");
                String msg = Objects.requireNonNull(response.getBody()).getMsg();
                taskDetailUpdate.setMsg(msg);
                taskDetailService.updateTaskDetail(taskDetailUpdate);
            }
        } catch (Exception e) {
            log.error("everyDayService error ", e);
        }
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ServiceResponse {
        private String code;
        private String msg;
        private String data;
    }
}
